﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL;
using CommontLibrary;
using System.Xml;
using System.Xml.Xsl;
using System.IO;

public partial class UserControl_HocVien_ListDeleteHistory : System.Web.UI.UserControl
{
    #region "Member variables"
    private int intUserID = 0;
    private int intUserList = 0;
    int intNhom = 0;
    int intChucNangID = 0;
    int intLevelID = 0;
    bool boolLevel2345678 = false;

    DALevel objLevel;
    DAQuyen objQuyen;
    DAHocVienLV2 objHocVienLV2;
    DAHocVienLV3LV5 objHocVienLV3LV5;
    DAHocVienLV6LV8 objHocVienLV6LV8;
    DAHocVienTrung objHocVien;
    DANguoidung objNguoidung;
    DATrangThai objTrangThai;
    DATrangThaiGoi objTrangThaiGoi;
    DALog objLog;
    DATruong objTruong;
    DataView m_dv_export_2_data = new DataView();
    #endregion
    #region "Parametter variables"
    // Ham lay Bind du lieu
    public SqlConnection ConnectionView
    {
        get
        {
            object obj2 = this.ViewState["ConnectionView"];
            if (obj2 != null)
            {
                return (SqlConnection)obj2;
            }
            return null;
        }
        set
        {
            this.ViewState["ConnectionView"] = value;
        }
    }
    #endregion
    #region "Private methods"
   
    private void BuildTreeSub1(DataRowCollection drLevels, ComponentArt.Web.UI.TreeViewNode parentNode, int intNguoiDung)
    {
        foreach (DataRow dr in drLevels)
        {
            int LevelID = Convert.ToInt32(dr["ID"].ToString());
            int intCount = objHocVien.loadDemSoHocVienTheoNguoiDung(intNguoiDung, LevelID);
            ComponentArt.Web.UI.TreeViewNode node = new ComponentArt.Web.UI.TreeViewNode();
            node.Text = dr["Ten"].ToString() + " (" + intCount.ToString() + ")";
            if (intLevelID == LevelID && intUserList == intNguoiDung)
            {
                node.CssClass = "SelectedTreeNode";
            }
            node.NavigateUrl = "Default.aspx?ChucNang=" + intChucNangID.ToString() + "&LevelView=" + dr["ID"].ToString() + "&UserList=" + intNguoiDung.ToString();
            node.ID = dr["Ma"].ToString();
            node.ImageUrl = "file.gif";
            parentNode.Nodes.Add(node);
        }
    }   
    // Builds a TreeView level containing the list of sub-folders of the given directory 
    private void BuildTreeSub(DataRowCollection drLevels, ComponentArt.Web.UI.TreeViewNode parentNode, int intNguoiDung,int NhomID)
    {
        foreach (DataRow dr in drLevels)
        {
            int LevelID = Convert.ToInt32(dr["ID"].ToString());
            int intCount = objHocVien.loadDemSoHocVienTheoNguoiDung(intNguoiDung, LevelID);
            ComponentArt.Web.UI.TreeViewNode node = new ComponentArt.Web.UI.TreeViewNode();
            node.Text = dr["Ten"].ToString() + " (" + intCount.ToString() + ")";
            if (intLevelID == LevelID && intUserList == intNguoiDung)
            {
                node.CssClass = "SelectedTreeNode";
            }
            node.NavigateUrl = "Default.aspx?ChucNang=" + intChucNangID.ToString() + "&Nhom=" + NhomID.ToString() + "&UserList=" + intNguoiDung.ToString() + "&LevelView=" + dr["ID"].ToString();
            //node.ID = dr["Ma"].ToString();
            node.ImageUrl = "file.gif";
            parentNode.Nodes.Add(node);
        }
    }   
    
    private void loadDemSoHocVienTheoThaiGoiByLevel(int LevelID,int intUserID)
    {
        try
        {
            DataSet dsTrangThai = objTrangThaiGoi.LayDanhSachTrangThaiGoi();
            DataSet dsTenTruong = objTruong.LayDanhSachTruong();
            this.rblTrangThaiGoi.Items.Clear();
            this.rblTenTruong.Items.Clear();
            ListItem liTemp = new ListItem();
            liTemp.Text = "Tất cả trạng thái";
            liTemp.Value = "0";
            liTemp.Selected = true;
            this.rblTrangThaiGoi.Items.Add(liTemp);
            this.rblTenTruong.Items.Add(liTemp);

            foreach (DataRow dr in dsTrangThai.Tables[0].Rows)
            {
                int intCountTrangThai = objHocVien.loadDemSoHocVienTheoThaiGoiByLevel(intUserID, LevelID, Convert.ToInt32(dr["ID"].ToString()));
                liTemp = new ListItem();
                liTemp.Text = dr["Ten"].ToString() + "(" + intCountTrangThai.ToString() + ")";
                liTemp.Value = dr["ID"].ToString();
                this.rblTrangThaiGoi.Items.Add(liTemp);
            }
            foreach (DataRow dr in dsTenTruong.Tables[0].Rows)
            {
                int intCountTenTruong = objHocVien.loadDemSoHocVienTheoThaiGoiByLevel(intUserID, LevelID, Convert.ToInt32(dr["ID"].ToString()));
                liTemp = new ListItem();
                liTemp.Text = dr["Ten"].ToString() + "(" + intCountTenTruong.ToString() + ")";
                liTemp.Value = dr["ID"].ToString();
                this.rblTenTruong.Items.Add(liTemp);
            }
        }
        catch
        { }
    }

    /// <summary>
    ///  /// Created by LinhDH
    /// Hàm này dùng để kiểm tra người dùng đăng nhập. 
    /// Nếu nằm trong danh sách cấm, không được xuất excel thì invisible nút xuất excel
    /// </summary>
    /// <returns>true nếu người dùng bị cấm; false nếu ng dùng ko bị cấm</returns>
    private bool check_quyen_xuat_excel()
    {
        string v_str_duong_dan_file;
        int v_i_flag = 0;
        v_str_duong_dan_file = Server.MapPath("~/UserControl/HocVien/DS_tai_khoan_khong_xuat_excel.txt");
        string[] v_str_danh_sach_nguoi_dung_cam = File.ReadAllLines(v_str_duong_dan_file);
        string v_str_account = Session["Username"].ToString();
        for (int v_i = 0; v_i < v_str_danh_sach_nguoi_dung_cam.Length; v_i++)
        {
            if (v_str_danh_sach_nguoi_dung_cam[v_i].Equals(v_str_account))
            {
                v_i_flag = 1;
                break;
            }
        }
        if (v_i_flag > 0) return true;  // Account đã bị cấm
        return false; // User ko bị cấm
    }

    private void loadTimDanhSachHocVien()
    {
        try
        {
            string HoTen =  this.txtTenHocVien.Text.Trim();
            string MaHocVien = this.txtMaHocVien.Text.Trim();
            string DienThoai = Utilities.chuan_hoa_so_dien_thoai(this.txtDienThoai.Text.Trim());
            string Email = this.txtEmail.Text.Trim();          
            DataView dv = new DataView();
            DataSet dsHocVien = objHocVien.loadTimDanhSachHocVienTVTS(HoTen, MaHocVien, DienThoai, Email,"DEL");
            if (ViewState["sortExpr"] != null)
            {
                //dv = new DataView(DateTimeUntil.ConvertTable(dsHocVien.Tables[0], false));
                dv = new DataView(dsHocVien.Tables[0]);
                dv.Sort = (string)ViewState["sortExpr"];
            }
            else
            {
                dv = new DataView(dsHocVien.Tables[0]);
            }
            this.grvHocVien.DataSource = dv;
            this.grvHocVien.DataBind();
        }
        catch(Exception v_e)
        { throw v_e; }
    }
    private void load_data_2_export_excel()
    {
        string HoTen = this.txtTenHocVien.Text.Trim();
        string MaHocVien = this.txtMaHocVien.Text.Trim();
        string DienThoai = Utilities.chuan_hoa_so_dien_thoai(this.txtDienThoai.Text.Trim());
        string Email = this.txtEmail.Text.Trim();
        //DataView dv = new DataView();
        DataSet dsHocVien = objHocVien.loadTimDanhSachHocVienTVTS(HoTen, MaHocVien, DienThoai, Email,"TRU");
        if (ViewState["sortExpr"] != null)
        {
            //dv = new DataView(DateTimeUntil.ConvertTable(dsHocVien.Tables[0], false));
            m_dv_export_2_data = new DataView(dsHocVien.Tables[0]);
            m_dv_export_2_data.Sort = (string)ViewState["sortExpr"];
        }
        else
        {
            m_dv_export_2_data = new DataView(dsHocVien.Tables[0]);
        }
    }

    // Xoa NguoiTimNguon
    private void DeleteNguoiTimNguon(object source, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int intHocVienID = Convert.ToInt32(grvHocVien.DataKeys[e.RowIndex].Value);
        int intChẹck = objHocVien.removeHocVien(intHocVienID);
        if (intChẹck > 0)
        {
            this.lblMess.Text = "Xóa thành công bản ghi";
            Session["UserID"] = intUserID;
            objLog.insertLog(0, intHocVienID, 16, intUserID);
            grvHocVien.EditIndex = -1;
            loadTimDanhSachHocVien();
        }
        else
        {
            this.lblMess.Text = "Lỗi trong quá trình xóa bản ghi!";
        }
    }
    public void SaveExcel(string strNamFile)
    {
        DataTable dt = new DataTable();
        load_data_2_export_excel();
        dt = m_dv_export_2_data.Table;
        dt.Columns.Add("NoidungCuocGoi");        
        for (int i =0; i < dt.Rows.Count ; i++)
        {
            int intHocVienID = Convert.ToInt32(dt.Rows[i]["ID"].ToString());
            if (intLevelID == 2)
            {
                
                DataRow dr = objHocVienLV2.loadHocVienLV2ID(intHocVienID, intLevelID);
                dt.Rows[i]["NoidungCuocGoi"] = dr["NoiDungNgayGoi"].ToString();
            }
            else if (intLevelID > 2 && intLevelID < 7)
            {
                DataRow dr = objHocVienLV3LV5.loadHocVienLV3LV5ID(intHocVienID, intLevelID);
                dt.Rows[i]["NoidungCuocGoi"] = dr["NoiDungNgayGoi"].ToString();
            }
            else if (intLevelID > 6 && intLevelID < 10)
            {
                DataRow dr = objHocVienLV6LV8.loadHocVienLV6LV8ID(intHocVienID, intLevelID);
                dt.Rows[i]["NoidungCuocGoi"] = dr["NoiDungNgayGoi"].ToString();
            }
            else
            {
                dt.Rows[i]["NoidungCuocGoi"] = "";
            }
        }

        string html = loadReportExportExcel(dt);
		Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
        Response.Clear();
        Response.AppendHeader("content-disposition", "attachment;filename=" + strNamFile);
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        this.EnableViewState = false;
        Response.Write("\r\n");
        Response.Write(html);
        Response.End();
    }
    public string loadReportExportExcel(DataTable dt)
    {
        try
        {
            string strHTML = "";
            strHTML += "\n  <col span=8 style='width:100%'>"; 
            strHTML += "\n      <tr>";
            strHTML += "\n          <td class=xl23 colspan=8>Danh Sách Ứng Viên</td>";
            strHTML += "\n      </tr>        ";
            strHTML += "\n      <tr > ";
            strHTML += "\n          <td class=xl24 style=\"width:8%;\" >STT</td>";
            strHTML += "\n          <td class=xl24>Họ tên</td>";
            strHTML += "\n          <td class=xl24 style=\"width:8%;\">Điện thoại</td>";
            strHTML += "\n          <td class=xl24 style=\"width:8%;\">Email</td>";
            strHTML += "\n          <td class=xl24 style=\"width:8%;\">Nội dung nhập trùng</td>";
            strHTML += "\n          <td class=xl24 style=\"width:8%;\">Tư vấn tuyển sinh</td>";
            strHTML += "\n          <td class=xl24>Thời gian nhập</td>";
            //strHTML += "\n          <td class=xl24>Tên Trường</td>";
            strHTML += "\n      </tr>";
            foreach (DataRow dr in dt.Rows)
            {
                strHTML += "\n  <tr >";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["Seq"].ToString() + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["HoTen"].ToString() + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + Utilities.dien_thoai_Output(dr["DienThoai"].ToString()) + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["Email"].ToString() + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["DiLam"].ToString() + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["GhiChuNguon"].ToString() + "</td>";
                strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["NgayNhap"].ToString() + "</td>";
                //strHTML += "\n      <td class=xl25 ><span class=\"cssLabel\">" + dr["TenTruong"].ToString() + "</td>";
                strHTML += "\n  </tr>";
            }
            strHTML = FileUntil.strFileExcel(strHTML);
            return strHTML;
        }
        catch
        {
            return "";
        }
    }
    #endregion
    #region "Events handle"
    //Check quyen han su dung
    private void CheckUserModule(int UserID, int ModuleID)
    {

    }
    private void loadDataAccess()
    {
        SqlConnection sqlConnec = ConnectData.getConnection();
        objHocVienLV2 = new DAHocVienLV2(sqlConnec);
        objHocVienLV3LV5 = new DAHocVienLV3LV5(sqlConnec);
        objHocVienLV6LV8 = new DAHocVienLV6LV8(sqlConnec);
        objHocVien = new DAHocVienTrung(sqlConnec);
        objNguoidung = new DANguoidung(sqlConnec);
        objTrangThaiGoi = new DATrangThaiGoi(sqlConnec);
        objTrangThai = new DATrangThai(sqlConnec);
        objLevel = new DALevel(sqlConnec);
        objQuyen = new DAQuyen(sqlConnec);
        objLog = new DALog(sqlConnec);
        objTruong = new DATruong(sqlConnec);
    }
    //Main load
    protected void Page_Load(object sender, EventArgs e)
    {
        loadDataAccess();
        intUserID = Convert.ToInt32(Session["UserID"].ToString());
        if (Request.QueryString["ChucNang"] != null)
        {
            bool boolCheck = StringUntil.checkNumber(Request.QueryString["ChucNang"].Trim());
            if (boolCheck)
            {
                intChucNangID = Convert.ToInt32(Request.QueryString["ChucNang"].Trim());
            }
        }
        if (Request.QueryString["Nhom"] != null)
        {
            bool boolCheck = StringUntil.checkNumber(Request.QueryString["Nhom"].Trim());
            if (boolCheck)
            {
                intNhom = Convert.ToInt32(Request.QueryString["Nhom"].Trim());
            }
        }
        if (Request.QueryString["LevelView"] != null)
        {
            bool boolCheck = StringUntil.checkNumber(Request.QueryString["LevelView"].Trim());
            if (boolCheck)
            {
                intLevelID = Convert.ToInt32(Request.QueryString["LevelView"].Trim());
            }
        }
        if (Request.QueryString["UserList"] != null)
        {
            bool boolCheck = StringUntil.checkNumber(Request.QueryString["UserList"].Trim());
            if (boolCheck)
            {
                intUserList = Convert.ToInt32(Request.QueryString["UserList"].Trim());
            }
        }
        //loadDemSoHocVienTheoThaiGoiByLevel(intLevelID, intUserList);
        //loadLevel();
        //loadTimDanhSachHocVien();
        if (!Page.IsPostBack)
        {
            try
            {
                loadTimDanhSachHocVien();               
               
                // nếu account đã bị khóa chức năng xuất excel
                if (check_quyen_xuat_excel()) btnInDanhSach.Visible = false;
                else btnInDanhSach.Visible = true;
            }
            catch
            { }
        }
    }

    //Su kien bin from NguoiTimNguon
    protected void grvHocVien_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
                e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
                // Modify     
                Label HocVienIDTemp = ((Label)e.Row.FindControl("HocVienID"));
                Label LevelIDTemp = ((Label)e.Row.FindControl("LevelID"));
                ImageButton lbtDeleteTemp = ((ImageButton)e.Row.FindControl("btnDelete"));
                if (lbtDeleteTemp != null)
                {
                    bool checkQuyen = false;

                    if (intUserID == 1)
                    {
                        checkQuyen = true;
                    }
                    else
                    {
                        DataSet dsNguoidung = objNguoidung.loadQuyenNguoidungbyNguoiDung(intUserID);
                        if (dsNguoidung != null && dsNguoidung.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in dsNguoidung.Tables[0].Rows)
                            {
                                if (dr["QuyenID"].ToString().Equals("1") || dr["QuyenID"].ToString().Equals("2"))
                                {
                                    checkQuyen = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (checkQuyen)
                    {
                        lbtDeleteTemp.Attributes.Add("Onclick", "javascript:if(confirm('Bạn chắc chắn muốn xóa OK , Bạn hủy lệnh CANCEL')) {return true} else {return false};");
                    }
                    //else if (Convert.ToInt32(LevelIDTemp.Text) == 1)
                    //{
                    //    lbtDeleteTemp.Attributes.Add("Onclick", "javascript:if(confirm('Bạn chắc chắn muốn xóa OK , Bạn hủy lệnh CANCEL')) {return true} else {return false};");
                    //}
                    else
                    {
                        lbtDeleteTemp.ImageUrl = "~/images/Button/NoDelete.gif";
                        lbtDeleteTemp.Enabled = false;
                    }
                }
                Label lblMaHocVienGVTemp = ((Label)e.Row.FindControl("lblMaHocVienGV"));                
                HyperLink hplUpdateGVTemp = ((HyperLink)e.Row.FindControl("hplUpdateGV"));

                Label lblNoidungGVTemp = ((Label)e.Row.FindControl("lblNoidungGV"));
                if (lblNoidungGVTemp != null)
                {
                    try
                    {
                        int intHocVienID = Convert.ToInt32(HocVienIDTemp.Text);
                        int intLevelID = Convert.ToInt32(LevelIDTemp.Text);
                        DataRow dr = null;
                        if (intLevelID == 2)
                        {
                            try
                            {
                                dr = objHocVienLV2.loadHocVienLV2ID(intHocVienID, intLevelID + 1);
                            }
                            catch
                            {
                                dr = objHocVienLV2.loadHocVienLV2ID(intHocVienID, intLevelID);
                            }
                        }
                        else if (intLevelID > 2 && intLevelID <= 6)
                        {
                            try
                            {
                                dr = objHocVienLV3LV5.loadHocVienLV3LV5ID(intHocVienID, intLevelID + 1);
                            }
                            catch
                            {
                                dr = objHocVienLV3LV5.loadHocVienLV3LV5ID(intHocVienID, intLevelID);
                            }

                        }
                        else if (intLevelID == 1)
                        {
                            try
                            {
                                dr = objHocVienLV2.loadHocVienLV2ID(intHocVienID, intLevelID + 1);
                            }
                            catch
                            {
                                dr = objHocVienLV2.loadHocVienLV2ID(intHocVienID, intLevelID);
                            }
                        }
                        else if (intLevelID > 6 && intLevelID < 10)
                        {
                            try
                            {
                                dr = objHocVienLV6LV8.loadHocVienLV6LV8ID(intHocVienID, intLevelID + 1);
                            }
                            catch
                            {
                                dr = objHocVienLV6LV8.loadHocVienLV6LV8ID(intHocVienID, intLevelID);
                            }
                        }
                        if (dr != null)
                        {
                            if (!dr["NoiDungTaiSao"].ToString().Trim().Equals(""))
                            {
                                lblNoidungGVTemp.Text = dr["NoiDungTaiSao"].ToString();
                            }
                            else
                            {
                                lblNoidungGVTemp.Text = dr["NoiDungNgayGoi"].ToString();
                            }
                        }
                        else
                        {
                            lblNoidungGVTemp.Text = "";
                        }
                    }
                    catch
                    {
                        lblNoidungGVTemp.Text = "";
                    }
                }
                
            }
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        loadTimDanhSachHocVien();
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        this.txtTenHocVien.Text = "";
        this.txtMaHocVien.Text = "";
        this.txtDienThoai.Text = "";
        this.txtEmail.Text = "";
        loadTimDanhSachHocVien();
    }
    protected void btnInDanhSach_Click(object sender, EventArgs e)
    {
        SaveExcel("Danhsachungvien" + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + ".xls");
    }
    //Su kien xoa NguoiTimNguon
    protected void grvHocVien_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        this.lblMess.Text = "";
        DeleteNguoiTimNguon(sender, e);
    }
    protected void grvHocVien_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.grvHocVien.EditIndex = -1;
        this.grvHocVien.PageIndex = e.NewPageIndex;
        loadTimDanhSachHocVien();
    }
    protected void rblTrangThaiGoi_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadTimDanhSachHocVien();
    }
    protected void rblTenTruong_SelectedIndexChanged(object sender, EventArgs e)
    {
        loadTimDanhSachHocVien();
    }
    protected void grvHocVien_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = " ASC";
        }
        else if (ViewState["SortOrder"].ToString() == " ASC")
        {
            ViewState["SortOrder"] = " DESC";
        }
        else
        {
            ViewState["SortOrder"] = " ASC";
        }
        ViewState["sortExpr"] = e.SortExpression + ViewState["SortOrder"];
        loadTimDanhSachHocVien();
    }
#endregion    
}
